var No_Result_Msg = "The results did not meet the requirements, please re-enter!";//Error Message
var PAGEID_ATTR = "pageId";
var QUESTION_ATTR = "q_";
var ANSWER_ATTR = "answer";
var thisHost = location.host;
var thisAppName = "api-client";
var serverPostUrl = "http://"+thisHost+"/"+thisAppName+"/";
var Corticon = {
	dialogRequestByExplicit : function(dialogInstanceId){
    	if (dialogInstanceId == ""){
    		alert("Please input DialogInstanceId Text.");
    		$("#dialogInstanceId").focus();
	        return false;
    	}else{
    		this.dialogRequestPostExplicit();
    	}
    
    },
    dialogRequestByImplicit : function(){    	
    	var THIS = this;
    	if ($("#sessionId").val() == "" && ($("#function").val() == "" && $("#productLine").val() == "" && $("#region").val() == "" && $("#locale").val() == "" && $("#status").val() == "" && $("#dateField").val() == "")) {
		   alert("Please choose at least on entry.");		   
		   return false;
        } else {         	         
	    	$.post(serverPostUrl+'api/dialogRequest.html',{        
			      mode: "implicit",
			      functions: $("#functions").val(),
			      product: $("#product").val(),
			      region: $("#region").val(),
			      locale: $("#locale").val(),
			      status: $("#status").val(),
			      effDate: $("#effDate").val(),
			      sessionId: $("#sessionId").val()			      
			},
			function(data) {
				//success										        
				if(data.length > 0 && data != '[null]'){					
					var jsonData = eval('(' + data + ')');					
					var errorFlag = jsonData.errorFlag;					
					var messages = jsonData.errorMessage;
					if (errorFlag == true){
						var msg ="";
						for(i=0;i<messages.length;i++){
							msg += messages[i].code+"\n";
						}
						alert(msg);
						return false;
					}else{
						window.location.href="api/rendenPage.html?rendenObj=dialogRequest";						
					}			    	     
				}else{            
					alert("No Pages matched the entered criteria");
					return false;
				}    
			});
        }
    },
    dialogRequestPostExplicit : function(){    	
    	$.post(serverPostUrl+'api/dialogRequest.html',{        
			      mode: "explicit",
			      dialogInstanceId: $("#dialogInstanceId").val()      
			},
			function(data) {
				//success							        
				if(data.length > 0 && data != '[null]'){					
					var jsonData = eval('(' + data + ')');					
					var errorFlag = jsonData.errorFlag;					
					var messages = jsonData.errorMessage;
					if (errorFlag == true){
						var msg ="";
						for(i=0;i<messages.length;i++){
							msg += messages[i].code+"\n";
						}
						alert(msg);
						return false;
					}else{
						window.location.href=serverPostUrl+"api/rendenPage.html?rendenObj=dialogRequest";						
					}			    	     
				}else{            
					alert("No Pages matched the entered criteria");
					return false;
				}    
			});    	
    },
    previousPage : function(dialogInstanceId,dialogId,pageId){ 
    	var pageName=$("#question").attr("name");   	    	
    	$.post(serverPostUrl+'api/navigatePage.html',{        
			  dialogInstanceId: dialogInstanceId,
		      dialogId: dialogId,
		      pageId:pageId,
		      navigation:'Prev',
		      pageName:"P-"+pageName      
			},
			function(data) {
				//success							        
				if(data.length > 0 && data != '[null]'){					
					var jsonData = eval('(' + data + ')');					
					var errorFlag = jsonData.errorFlag;					
					var messages = jsonData.errorMessage;
					if (errorFlag == true){
						var msg ="";
						for(i=0;i<messages.length;i++){
							msg += messages[i].code+"\n";
						}
						alert(msg);
						return false;
					}else{
						window.location.href=serverPostUrl+"api/rendenPage.html?rendenObj=navigatePage";						
					}			    	     
				}else{				
					window.location.href=serverPostUrl+"index.jsp";
				}    
			}); 	
    },
    nextPage : function(dialogInstanceId,dialogId,pageId){    	
    	var THIS = this;
    	var flag = true;
	        var questions = THIS.getAllQuestion();
	        var answer="";          
	        questions.each(function() {
	        	answer = "";
	        	var errorFlag = $(this).attr("class");	        	
	            var questionId = $(this).attr("id");
	            questionId = questionId.replace("q_", "");
	            var answerObject = $("#answer"+questionId);	 
	            $("#error").html("");
            	$("#error"+$(this).attr("id")).text("");
            	$(this).attr("class","box");
	            if (answerObject.length > 0){
		            var answerType = answerObject.attr("type");		                  
		            if (answerType == 'radio'){
		                answer = $('input[@id=answer'+questionId+'][@checked]').val();                
		            }
		            if (answerType == 'text'){
		                answer = $("#answer"+questionId).val();
		            }   
		            if (answerType == 'textarea'){
		                answer = $("#answer"+questionId).attr("value");
		                if (answer.length ==0){
		                	answer = $("#answer"+questionId).text();
		                }		               
		            }
		            if (answerType == 'checkbox'){            	
		            	$(":checkbox[name=answer"+questionId+"]:checked").each(function(){
				        	answer = $(this).val();			                     
				    	});                 
		            }  
		            if (answerType == 'select-one'){
		                answer = $("#answer"+questionId).val();
		            } 		            
		            if (answer == undefined){
		                answer = "";
		            }	
		            
		            if (answer.length == 0){	            	
		            	$("#error").html("");
		            	$("#error"+$(this).attr("id")).text("This question is required.");        			
        				$(this).attr("class","box_error");
		            	flag = false;		            	
		            }else{
		            	if (answerType == 'text' || answerType == 'textarea'){
			            	var minChar = $("#answer"+questionId).attr("minChar");
			            	var maxChar = $("#answer"+questionId).attr("maxChar");
			            	//alert("minChar="+minChar+";maxChar="+maxChar+";length="+answer.length);
			            	if (minChar != "" && maxChar != ""){
			            		if (answer.length < Number(minChar) && answer.length > Number(maxChar)){
			            			$("#error").html("");
					            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters and "+maxChar+" character maximum!");        			
			        				$(this).attr("class","box_error");
					            	flag = false;
			            		}
			            		if (answer.length < Number(minChar)){
			            			$("#error").html("");
					            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters!");        			
			        				$(this).attr("class","box_error");
					            	flag = false;
			            		}
			            		if (answer.length > Number(maxChar)){
			            			$("#error").html("");
					            	$("#error"+$(this).attr("id")).text("This question of the maximum number of characters is "+maxChar);        			
			        				$(this).attr("class","box_error");
					            	flag = false;
			            		}			            		
			            	}
			            }else{
			            	$("#error").html("");
			            	$("#error"+$(this).attr("id")).text("");
			            	$(this).attr("class","box");
			            }
		            }	
	            }            
	        });	
    	if (flag){  
	        leaveFlag = false;
	        THIS.jumpPage(dialogInstanceId,dialogId,pageId);
	        //THIS.nextPageOnly(dialogInstanceId,dialogId,pageId);		       
	    }else{
	       return false;
	    }
    }, 
    nextPageOnly : function(dialogInstanceId,dialogId,pageId){  
    	var pageName=$("#question").attr("name"); 		
    	$.post(serverPostUrl+'api/navigatePage.html',{        
			  dialogInstanceId: dialogInstanceId,
		      dialogId: dialogId,
		      pageId:pageId,
		      navigation:'Next',
		      pageName:"P-"+pageName      
			},
			function(data) {
				//success							        
				if(data.length > 0 && data != '[null]'){					
					var jsonData = eval('(' + data + ')');					
					var errorFlag = jsonData.errorFlag;					
					var messages = jsonData.errorMessage;
					if (errorFlag == true){
						var msg ="";
						for(i=0;i<messages.length;i++){
							msg += messages[i].code+"\n";
						}
						alert(msg);
						return false;
					}else{					
						window.location.href=serverPostUrl+"api/rendenPage.html?rendenObj=navigatePage";						
					}			    	     
				}else{				
					window.location.href=serverPostUrl+"api/dialogReport.html?dialogInstanceId="+dialogInstanceId+"&sessionId=";
				}    
			}); 	
    },
    jumpPage : function(dialogInstanceId,dialogId,pageId){
    	var lastid = "";
    	var pageinquestionId = "";
    	var lastanswerId = "";
    	var qnId = $("#qnId").val();
    	var questions = this.getAllQuestion();
        var lastQuestion = questions[questions.length - 1];
        var questionId = $(lastQuestion).attr("id");
        pageinquestionId = $(lastQuestion).attr("pageinquestionid");
        questionId = questionId.replace("q_", "");
        var answerType = $("#answer"+questionId).attr("type");
        var answer="";
        if (answerType == 'radio'){
            answer = $('input[@id=answer'+questionId+'][@checked]').val();
        }
        if (answerType == 'text'){
            answer = $("#answer"+questionId).val();
        }
        if (answerType == 'textarea'){
            answer = $("#answer"+questionId).attr("value");
            if (answer.length ==0){
            	answer = $("#answer"+questionId).text();
            }		               
        }
        if (answerType == 'checkbox'){
            $(":checkbox[name=answer"+questionId+"]:checked").each(function(){
                answer = $(lastQuestion).val();
            });
        }
        if (answerType == 'select-one'){
            answer = $("#answer"+questionId).val();
        }
        if (answer == undefined){
            answer = "";
        }
        var questionList = questionId.split("-");
        lastid = questionList[2];
        lastanswerId = answer;
        return this.processResponse(dialogInstanceId,dialogId,pageId,lastid,lastanswerId,pageinquestionId,'',true);
        
    },      
    processResponse : function(dialogInstanceId,dialogId,pageId,lastQuestionId,answerId,pageinquestionId,responseId,isNextPage){
    	var THIS = this; 
    	$("#warningLarge").hide(); 
    	$("#error").html("");
    	this.resetError();
    	this.greyText(dialogId+"-"+pageId+"-"+lastQuestionId);    	
    	var lastid = "";
    	var dataList = [];
        var questions = this.getAllQuestion();   
        var flag = true;
        questions.each(function() {
            var questionId = $(this).attr("id");
            questionId = questionId.replace("q_", "");
            var answerType = $("#answer"+questionId).attr("type");            
            var answer="";                     
            if (answerType == 'radio'){
                answer = $('input[@id=answer'+questionId+'][@checked]').val();                	                
            }
            if (answerType == 'text'){
                answer = $("#answer"+questionId).val();                 
            }   
            if (answerType == 'textarea'){
                answer = $("#answer"+questionId).attr("value");
                if (answer.length ==0){
                	answer = $("#answer"+questionId).text();
                }		               
            }
            if (answerType == 'select-one'){
                answer = $("#answer"+questionId).val();                 
            }          
            if (answer == undefined){
                    answer = "";
            }         
            if (answerType == 'text' || answerType == 'textarea'){
            	var minChar = $("#answer"+questionId).attr("minChar");
            	var maxChar = $("#answer"+questionId).attr("maxChar");
            	//alert("minChar="+minChar+";maxChar="+maxChar+";length="+answer.length);
            	if (minChar != "" && maxChar != ""){
            		if (answer.length < Number(minChar) && answer.length > Number(maxChar)){
            			$("#error").html("");
		            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters and "+maxChar+" character maximum!");        			
        				$(this).attr("class","box_error");
		            	flag = false;
            		}
            		if (answer.length < Number(minChar)){
            			$("#error").html("");
		            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters!");        			
        				$(this).attr("class","box_error");
		            	flag = false;
            		}
            		if (answer.length > Number(maxChar)){
            			$("#error").html("");
		            	$("#error"+$(this).attr("id")).text("This question of the maximum number of characters is "+maxChar);        			
        				$(this).attr("class","box_error");
		            	flag = false;
            		}			            		
            	}
            }
            var responseId = $(this).attr('responseId');                  
            if (answer != ""){
             	var questionList = questionId.split("-");
	            lastid = questionList[2];
            	var item = '{"pageId":"'+questionList[1]+'","questionId":"'+questionList[2]+'","responseValue":"'+answer+'","pageinquestionId":'+$(this).attr('pageInQuestionID')+'}';            	           	
                dataList.push(item);
            }        
        });  
        if (flag == false){        	
        	THIS.resetQuestion(dialogId+"-"+pageId+"-"+lastQuestionId,answerId); 
        	return false;
        }
        $(":checkbox[name^=answer]:checked").each(function(){        	
        	var questionList = $(this).attr('id').split("-");      	           
        	var item = '{"pageId":"'+questionList[1]+'","questionId":"'+questionList[2]+'","responseValue":"'+$(this).val()+'","pageinquestionId":'+$(this).attr('pageInQuestionID')+',"answerId":'+$(this).val()+'}';
            dataList.push(item);             		             
    	});
    	       	
        var lastType = $("#answer"+dialogId+"-"+pageId+"-"+lastQuestionId).attr("type");       
        if (lastType == "checkbox"){
	        $('input[@id="answer'+dialogId+"-"+pageId+"-"+lastQuestionId+'"][@checked=""]').each(function(){
					if ($(this).val() == answerId){	
						var questionId = $(this).attr("id");
            			questionId = questionId.replace("q_", "");
            			var questionList = questionId.split("-");
						var item = '{"pageId":"'+questionList[1]+'","questionId":"'+questionList[2]+'","responseValue":"","pageinquestionId":'+$(this).attr('pageInQuestionID')+',"answerId":'+$(this).val()+'}';
		            	//var item = "{'id':" + $(this).attr('id') + ",'responseId':'"+$(this).attr('responseId')+"','pageInQuestionID':'"+$(this).attr('pageInQuestionID')+"','answerId':''}";
            			dataList.push(item);
		            }	           
			});
        } 
        
    	var questionData = "";    	
    	if (dataList.toString()==""){    		
    		var response = '[{"pageId":"'+pageId+'","questionId":"'+lastQuestionId+'","responseValue":"'+answerId+'","pageinquestionId":'+pageinquestionId+'}]';
    		questionData = '[{"dialogInstanceId":"'+dialogInstanceId+'","dialogId":"'+dialogId+'","pageId":"'+pageId+'","lastquestionId":"'+lastQuestionId+'","response":'+response+',"nextPage":"'+isNextPage+'"}]';
    	}else{    	
    	//set questionData
    		questionData = '[{"dialogInstanceId":"'+dialogInstanceId+'","dialogId":"'+dialogId+'","pageId":"'+pageId+'","lastquestionId":"'+lastQuestionId+'","response":'+"[" + dataList.toString() + "]"+',"nextPage":"'+isNextPage+'"}]';
    	}     	
    	$.blockUI({message:"Waiting......"});
    	$("#warningLarge").hide();     	
    	var dialogInstanceId1 = dialogInstanceId;
    	var dialogId1=dialogId;
    	var pageId1 = pageId;
    	var questionId1 = lastQuestionId; 
    	var lastQuestionName = $("#q_"+dialogId+"-"+pageId+"-"+lastQuestionId).attr("name");	
    	
    	$.post(serverPostUrl+'api/processResponse.html?r='+Math.random(),{	      
		      questionData:questionData,
		      lastQuestionName:"Q-"+lastQuestionName
		},
		function(data) {			 	
        	var noOfChangedFlag = data.noOfChangedFlag;        	
        	if (noOfChangedFlag<0){       		
        		$("#error").html();       		      		
        		var messages = data.errorMessage;
        		for(i=0;i<messages.length;i++){
        			try{	        			
	        			var msg = messages[i].code;	        			        			  			
	        			var ErrorQuestion = messages[i].questionId;	        			
	        			if($("#errorq_"+dialogId1+"-"+pageId1+"-"+ErrorQuestion).length>0){
		        			$("#errorq_"+dialogId1+"-"+pageId1+"-"+ErrorQuestion).text(msg);        			
		        			$("#q_"+dialogId1+"-"+pageId1+"-"+ErrorQuestion).attr("class","box_error");
	        			}else{	        				
	        				$("#error").html("<li>"+msg+"</li>");
	        				$("#warningLarge").show();	        				
	        			}
	        			  
        			}catch(err){
        				$("error").html($("error").html()+"<li>"+messages+"</li>");        				
        			}      			
        		}
        		
        		var currentClass = $("#q_"+dialogId1+"-"+pageId1+"-"+questionId1).attr("class"); 
        		if (currentClass == "box_active"){
        			$("#q_"+dialogId1+"-"+pageId1+"-"+questionId1).attr("class","box"); 
        		}  		
        		
        		$.unblockUI();
        		//Reset This Question Form
        		if (isNextPage == false){
        			THIS.resetQuestion(dialogId1+"-"+pageId1+"-"+questionId1,answerId); 
        		}        		      		
        		return false;
        	}        	
        	if (noOfChangedFlag>=0){
        		var dialogId = data.dialogId;
        		var pageId = data.page.pageId;            	          	
            	var questions = data.question;             	            	         	
            	for(i=0;i<questions.length;i++){            		
            		var questionId = questions[i].questionId;            		
            		var questionDisplayFlag = questions[i].displayFlag;
            		var seq = questions[i].sequence;             		
            		var responses = questions[i].responseEntry;
            		var reloadFlag = questions[i].reload;
            		var displayValue;            		
            		if (responses!=null || responses!=""){
	            		var responseValue = data.question[i].answerValue; 	            		
	            		var pageInQuestionId = data.question[i].questionPageId; 
	            		var responseType = data.question[i].responseType;	            		
            		}            		
            		if (responseType == "Display"){
            			displayValue = responses[0].value;            			
            		}
            		if (questionDisplayFlag == false){            			          		
            			if($("#q_"+dialogId+"-"+pageId+"-"+questionId).length>0){
            				$("#q_"+dialogId+"-"+pageId+"-"+questionId).remove();                          
            			}
            		}            		
            		if (questionDisplayFlag == true){            			          			            		       			
	            		if($("#q_"+dialogId+"-"+pageId+"-"+questionId).length>0){	            			
	            			//Display	            				            				            			
	            			if ((displayValue!="" && responseType =="Display" && seq.indexOf(".")>0 && isNextPage == false)  || (responseType == "Dynamic" && reloadFlag == true && isNextPage == false)){
	            				$("#q_"+dialogId+"-"+pageId+"-"+questionId).remove();
	            				var showQuestion=THIS.jsonToString(data.question[i]);	            			  						
		            			THIS.showDiv(showQuestion,dialogInstanceId,dialogId,pageId);
	            			}            			           			
	            			$("#q_"+dialogId+"-"+pageId+"-"+questionId).show();
	            		}else{	            			         			       			
	            			var showQuestion=THIS.jsonToString(data.question[i]);	            			
	            			THIS.showDiv(showQuestion,dialogInstanceId,dialogId,pageId);	            			        			
	            		}            			
            		}
            	}
        	}        	
            if (isNextPage == true){
            	THIS.nextPageOnly(dialogInstanceId,dialogId,pageId);
            }           
            
        	$.unblockUI();
		}, "json");		
    },
    showDiv : function(paramJson,dialogInstanceId,dialogId,pageId){    	
    	var THIS = this;   
        $.post(serverPostUrl+"api/showDiv.html?r="+Math.random(), {
            paramJson: paramJson,
            dialogInstanceId: dialogInstanceId,
            dialogId: dialogId,
            pageId: pageId          
        }, function (data) {         	     	
        	var pageId = "";
            var pagePix = "";            
            if (data.length >0){
                pageId = data.substr(data.indexOf(PAGEID_ATTR+"="),20);                
                pagePix = pageId.substring(pageId.indexOf("\"")+1,pageId.lastIndexOf("\""));
                pageId = pageId.substring(pageId.indexOf("\"")+1,pageId.lastIndexOf("-"));               			
                var flag = true;
                var displayDiv = "";                             
                var likeQuestion = THIS.getAllQuestion();                 
                if (likeQuestion.length == 0){
                    $("#question"+pageId).append(data);
                }else{
                    likeQuestion.each(function () {                    	
                        if (flag){
                            var thisPageId = $(this).attr(PAGEID_ATTR);                            
                            if (THIS.compareSequence(thisPageId,pagePix)) {                            	
                                flag = false;
                                $(this).before(data);
                            }
                        }
                    });                    
                    if (flag){
                    	$("[id^=question]").append(data);
                    }
                }
            }  
        });
    },
    getAllQuestion : function(){
        return $("[id^=" + QUESTION_ATTR + "]");
    },
    getAllErrorQuestion : function(){
    	return $("[class=box_error]");
    },
    getAllError : function(){
    	return $("[id^=error]");
    },
    findNextDynamic : function(){
    
    },
    compareSequence : function(ThisPageId,OtherPageId){
        var thisLevel = this.calcLevel(ThisPageId);
        var otherLevel = this.calcLevel(OtherPageId);
        var proportion = 1;
        if (thisLevel <= otherLevel){
            thisLevel = otherLevel;
        }
        for(i=0;i<thisLevel;i++){
            proportion = proportion*10;
        }    
       
        ThisPageId = ThisPageId.substr(ThisPageId.indexOf("-")+1);
        OtherPageId = OtherPageId.substr(OtherPageId.indexOf("-")+1);
        ThisPageId = this.magicNumber(ThisPageId);
        OtherPageId = this.magicNumber(OtherPageId);        
        if (ThisPageId*proportion > OtherPageId*proportion){
            return true;
        }else{
            return false;
        }
    },
    magicNumber : function(Str){
        var Level = this.calcLevel(Str);
        if (Level >1){
            var proportion = 1;
            for(i=0;i<Level;i++){
                proportion = proportion*10;
            }
            var newStr = Str.replace(/\D/g,"");
            var Str4Number = newStr*10/proportion;
            return Str4Number;
        }else{
            return Str;
        }
    },
    calcLevel : function(sequence){
        return sequence.replace(/[^\.]/g, "").length + 1;
    },
    ShowHelp : function(obj,itemId){
    	this.hideAllHelp(itemId);
        var display = $("#help_"+itemId).css("display");
        var helpCss = $("#help_"+itemId).attr("class");
        if (helpCss == "help help_rt"){
            $("#help_"+itemId).removeClass("help help_rt");
            $("#help_"+itemId).addClass("help");
        }        
        if (display == "none"){
            var screenWidth = screen.width;
            if (this.getItemY(obj)+$("#help_"+itemId).width() >= screenWidth){
                $("#help_"+itemId).removeClass("help");
                $("#help_"+itemId).addClass("help help_rt");
                $("#help_"+itemId).css("top",(this.getItemX(obj)-40)+"px");
                $("#help_"+itemId).css("left",(this.getItemY(obj)-$("#help_"+itemId).width())+"px");
            }else{
                $("#help_"+itemId).css("top",(this.getItemX(obj)-40)+"px");
                $("#help_"+itemId).css("left",(this.getItemY(obj)+obj.width)+"px");
            }
            $("#help_"+itemId).show();
        }else{
            $("#help_"+itemId).hide();
        }
    },
    getItemX :function(item){
        var offset=item.offsetTop;
        if(item.offsetParent!=null) {
            offset+=this.getItemX(item.offsetParent);
        }
        return offset;
    },
    getItemY : function(item){
        var offset=item.offsetLeft;
        if(item.offsetParent!=null) {
            offset+=this.getItemY(item.offsetParent);
        }
        return offset;
    },
    hideAllHelp : function(itemId){
    	var allHelp = this.getAllHelp();
    	if (allHelp.length > 0){
    		allHelp.each(function() {    			
    			if($(this).attr("id")!= "help_"+itemId){
    				$(this).hide();
    			}    			
    		});
    	}
    },
    getAllHelp : function(){
        return $("[id^=help_]");
    },
    greyText : function(itemId){
    	var isInput = $("#answer"+itemId).val(); 
    	if (isInput == undefined){
    		return true;
    	}   	
    	if (isInput.length>0){
    		$("#q_"+itemId).attr("class","box");
    		$("#errorq_"+itemId).text(""); 
    		return false;
    	}
    	return false;    	
    },
    jsonToString: function(obj){
    	var THIS = this; 
        switch(typeof(obj)){
            case 'string':
                return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
            case 'array':
                return '[' + obj.map(THIS.jsonToString).join(',') + ']';
            case 'object':
                 if(obj instanceof Array){
                    var strArr = [];
                    var len = obj.length;
                    for(var i=0; i<len; i++){
                        strArr.push(THIS.jsonToString(obj[i]));
                    }
                    return '[' + strArr.join(',') + ']';
                }else if(obj==null){
                    return 'null';

                }else{
                    var string = [];
                    for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));
                    return '{' + string.join(',') + '}';
                }
            case 'number':
                return obj;
            case false:
                return obj;
        }
    },
    resetQuestion : function(questionId,answerValue){    	 			  	      
	     var answerType = $("#answer"+questionId).attr("type");	     
		 if (answerType == 'checkbox'){
		   	$(":checkbox[name=answer"+questionId+"]").each(function() {
			     if (answerValue == $(this).val()){
			        $(this).attr("checked","");			            									
			     }                                      
             });
		  }
		 if (answerType == 'radio'){
		    $('input[@id=answer'+questionId+'][@checked]').attr("checked",'');                
		  }
		 if (answerType == 'select-one'){
		    $("#answer"+questionId).val("");
		 }         
    },
    resetError : function(){       	      
	     var errorQuestions = this.getAllErrorQuestion();
	     errorQuestions.each(function(){
	     	$(this).attr("class","box");
	     });
	     var errors = this.getAllError();
	     errors.each(function () {
	     	$(this).text("");
	     }); 	                      
    },

    finish : function(dialogId,exitPageURL) {
        var completedFlag = true;
        var questions = this.getAllQuestion();
        var answer = "";
        questions.each(function() {
            var questionId = $(this).attr("id");
            questionId = questionId.replace("q_", "");
            var answerObject = $("#answer" + questionId);
            $("#error").html("");
        	$("#error"+$(this).attr("id")).text("");
        	$(this).attr("class","box");
            if (answerObject.length > 0) {
                var answerType = answerObject.attr("type");

                if (answerType == 'radio') {
                    answer = $('input[@id=answer' + questionId + '][@checked]').val();
                }
                if (answerType == 'text') {
                    answer = $("#answer" + questionId).val();
                }
                if (answerType == 'textarea'){
	                answer = $("#answer"+questionId).attr("value");
	                if (answer.length ==0){
	                	answer = $("#answer"+questionId).text();
	                }		               
	            }
                if (answerType == 'checkbox') {
                    $(":checkbox[name=answer"+questionId+"]:checked").each(function(){
                        answer = $(this).val();
                    });
                }
                if (answerType == 'select-one') {
                    answer = $("#answer" + questionId).val();
                }
                if (answer == undefined) {
                    answer = "";
                }
                if (answer.length == 0){
                    $("#error").html("");
                    $("#error"+$(this).attr("id")).text("This question is required.");
                    $(this).attr("class","box_error");
                    completedFlag = false;
                }else{
                	if (answerType == 'text' || answerType == 'textarea'){
		            	var minChar = $("#answer"+questionId).attr("minChar");
		            	var maxChar = $("#answer"+questionId).attr("maxChar");
		            	//alert("minChar="+minChar+";maxChar="+maxChar+";length="+answer.length);
		            	if (minChar != "" && maxChar != ""){
		            		if (answer.length < Number(minChar) && answer.length > Number(maxChar)){
		            			$("#error").html("");
				            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters and "+maxChar+" character maximum!");        			
		        				$(this).attr("class","box_error");
				            	flag = false;
		            		}
		            		if (answer.length < Number(minChar)){
		            			$("#error").html("");
				            	$("#error"+$(this).attr("id")).text("This question at least "+minChar+" characters!");        			
		        				$(this).attr("class","box_error");
				            	flag = false;
		            		}
		            		if (answer.length > Number(maxChar)){
		            			$("#error").html("");
				            	$("#error"+$(this).attr("id")).text("This question of the maximum number of characters is "+maxChar);        			
		        				$(this).attr("class","box_error");
				            	flag = false;
		            		}			            		
		            	}
		            }else{
		            	$("#error").html("");
		            	$("#error"+$(this).attr("id")).text("");
		            	$(this).attr("class","box");
		            }
	            }
            }
        });
        if (completedFlag==true) {
            if (confirm("Are you sure? Once you click 'OK', you will no longer be able to modify your answers."))
            	if (exitPageURL == ""){
            		return false;
            	}else{
                	window.location.href = exitPageURL;
                }                
        } else {
            return false;
        }
    }
}